﻿using Common.Contract;
using Common.Contract.Customer.Request.PortfolioManagement;
using Common.Service.Command;
using Customer.Model.Interface;
using Customer.Model.Model;
using Newtonsoft.Json;
using System;

namespace Customer.Core.ServiceCommand.PortfolioManagement
{
    public class UpdateAccountPlanningServiceCommand : ProviderServiceCommand<IProviderFactory, UpdateAccountPlanningRequest, ResponseRecord>
    {
        public UpdateAccountPlanningServiceCommand(IProviderFactory providers) : base(providers) { }
        protected override void Validate(UpdateAccountPlanningRequest request)
        {
            if (request == null) throw new ArgumentNullException("request");
            if (!request.Header.ApplicationKey.HasValue || request.Header.ApplicationKey == Guid.Empty)
            {
                throw new ArgumentException("ApplicationKey must be set", "request");
            }
            if (request.Record == null)
            {
                throw new ArgumentException("Record must be set", "request");
            }
        }

        protected override bool OnExecute(ResponseRecord response)
        {
            bool isUpdate = true;
            var record = Request.Record;
            AccountPlanningHistory lastChange = Providers.Portfolios.RetrieveLastChangeByCif(record.DaoCif, 1);

            var obj = new AccountPlanning
            {
                Cif = record.Cif,
                ActionPlanT62016 = record.ActionPlanT62016,
                Industry = record.Industry,
                PaymentMethod = record.PaymentMethod,
                WalletShare = record.WalletShare,
                SpBanCheo = record.SpBanCheo,
                VuongMac = record.VuongMac,
                KhHoTro = record.KhHoTro,
                MainSector = record.MainSector,
                Status = 1
            };
            var jsonString = JsonConvert.SerializeObject(obj);
            AccountPlanningHistory objHis = new AccountPlanningHistory
            {
                Value = jsonString,
                Type = 1,
                ChangeDate = DateTime.Now,
                DaoChange = record.DaoCif,
                Cif = record.Cif,
                Id = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds
            };
            if (lastChange == null || !lastChange.Value.Equals(objHis))
            {
                isUpdate = Providers.Portfolios.UpdateAccountPlanning(obj) && Providers.Portfolios.SaveAccountPlanningHistory(objHis);
            }

            return isUpdate;
        }
    }
}
